package org.hackystat.storageservice.resources.alt;

import org.hackystat.sensorbase.resource.projects.jaxb.ProjectSummary;
import org.hackystat.storageservice.db.derby.DerbyFacade;
import org.hackystat.utilities.tstamp.Tstamp;
import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by IntelliJ IDEA.
 * User: STE2112
 * Date: 07-05-2011
 * Time: 14:53:20
 * To change this template use File | Settings | File Templates.
 */
public class UserProjectSummaryResource extends Resource {
    private String startTime;
    private String endTime;
    private DerbyFacade db;
    private Util util;

    /**
     * Provides the following representational variants: TEXT_XML.
     *
     * @param context  The context.
     * @param request  The request object.
     * @param response The response object.
     */
    public UserProjectSummaryResource(Context context, Request request, Response response) {
        super(context, request, response);
        System.out.println("UserProjectSummaryResource.UserProjectSummaryResource");
        this.startTime = (String) request.getAttributes().get("startTime");
        this.endTime = (String) request.getAttributes().get("endTime");
        this.util = new Util(request, response);
        db = (DerbyFacade) getContext().getAttributes().get("DerbyFacade");
        getVariants().clear();
        getVariants().add(new Variant(MediaType.TEXT_XML));

    }

    /**
     * Returns an XML representation of the ProjectSummary associated with this User.
     * <ul>
     * <li> The uriUser must be defined as a User.
     * <li> The Project must be defined for this User.
     * <li> The authenticated user must be the admin, or uriUser, or a member of the project, or
     * invited to be in the Project.
     * <li> There must be a startTime and endTime parameters which are timestamps.
     * </ul>
     *
     * @param variant The representational variant requested, or null if conditions are violated.
     * @return The representation.
     */
    @Override
    public Representation represent(Variant variant) {
        System.out.println("UserProjectSummaryResource.represent");
        XMLGregorianCalendar startTimeXml;
        XMLGregorianCalendar endTimeXml = null;
        // Parse this.startTime, this.endTime, and this.numDays
        try {
            startTimeXml = Tstamp.makeTimestamp(this.startTime);
        }
        catch (Exception e) {
            util.setStatusBadTimestamp(this.startTime);
            return null;
        }
        try {
            if (this.endTime != null) {
                endTimeXml = Tstamp.makeTimestamp(this.endTime);
            }
        }
        catch (Exception e) {
            util.setStatusBadTimestamp(this.endTime);
            return null;
        }

        try {
            Map<String,Object> attributes = getRequest().getAttributes();
            System.out.println("Attributes\n" + attributes);
            String userEmailList = (String) attributes.get("userEmailList");
            System.out.println("userEmailList = " + userEmailList);
            List<String> userEmails = toStringList(userEmailList);
            String href = (String) attributes.get("href");
            System.out.println("href = " + href);
            String uriPatterns = (String) attributes.get("uriPatternList");
            List<String> uriPatternList = toStringList(uriPatterns);
            ProjectSummary summary = db.getProjectSummary(userEmails, startTimeXml, endTimeXml, uriPatternList, href);
            Marshaller marshaller = JAXBContext.newInstance(org.hackystat.sensorbase.resource.projects.jaxb.ObjectFactory.class).createMarshaller();
            StringWriter result = new StringWriter();
            marshaller.marshal(summary, result);
            System.out.println("Result before converting to StringRepresentation:\n" + result.toString());
            return Util.getStringRepresentation(result.toString(), false);
        }
        catch (Exception e) {
            util.setStatusInternalError(e);
        }
        return null;
    }

    private List<String> toStringList(String string) {
        List<String> res = new ArrayList<String>();
        res.addAll(Arrays.asList(string.split(",")));
        return res;
    }
}
